/**
 	TreeCheckboxController class
 */
package nrb.utils
{
	import mx.events.TreeEvent;
	import nrb.components.it.sephiroth.renderers.TreecheckboxItemRenderer;
	
	public class TreeCheckboxController {
		
		
		/**
		 	Type: Controller
		 	@Params:none
		 	@return:none
		 	Desc:
		 */
		public function TreeCheckboxController(){
			
		}
		
		
		/**
		 * Called on checkbox click
		 * check and update for both parents and child nodes
		 * according to the checkbox status
		 */
		public function onItemCheck( event: TreeEvent ): void
		{
			updateParents( event.item as XML, ( event.itemRenderer as TreecheckboxItemRenderer ).checkBox.checkState );
			updateChilds( event.item as XML, ( event.itemRenderer as TreecheckboxItemRenderer ).checkBox.checkState );
		}
		
		/**
		 * @see it.sephiroth.controls.CheckBoxExtended#checkState
		 * 
		 */
        public function updateChilds( item:XML, value: uint ):void
        {
	        var middle: Boolean = ( value & 2 << 1 ) == ( 2 << 1 );
	        var selected: Boolean = ( value & 1 << 1 ) == ( 1 << 1 );
        
            if( item.children( ).length( ) > 0 && !middle )
            {
                for each(var x: XML in item.node )
                {
                    x.@checked = value == ( 1 << 1 | 2 << 1 ) ? "2" : value == ( 1 << 1 ) ? "1" : "0";
                    updateChilds( x, value );
                }
            }
        }
        
        public function updateParents( item: XML, value: uint ): void
        {
        	var checkValue: String = ( value == ( 1 << 1 | 2 << 1 ) ? "2" : value == ( 1 << 1 ) ? "1" : "0" );
            var parentNode: XML = item.parent( );
            if( parentNode )
            {
                for each(var x: XML in parentNode.node )
                {
                    if( x.@checked != checkValue )
                    {
                        checkValue = "2"
                    }
                }
                parentNode.@checked = checkValue;
                updateParents( parentNode, value );
            }
        }
		
	}
}